package com.bootx.controller.api;

import com.bootx.common.Result;
import com.bootx.controller.BaseController;
import com.bootx.entity.BaseEntity;
import com.bootx.entity.WriteTool;
import com.bootx.entity.WriteToolTask;
import com.bootx.service.WriteToolService;
import com.bootx.service.WriteToolTaskService;
import com.fasterxml.jackson.annotation.JsonView;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/writeToolTask")
public class WriteToolTaskController extends BaseController {

    @Resource
    private WriteToolService writeToolService;

    @Resource
    private WriteToolTaskService writeToolTaskService;

    @PostMapping("/create")
    public Result create(Long writeToolId,String content,String params){
        WriteTool writeTool = writeToolService.find(writeToolId);
        WriteToolTask writeToolTask = new WriteToolTask();
        if(StringUtils.isBlank(content)){
            writeToolTask.setContent(params);
            writeToolTask.setUserInputType(1);
        }else {
            writeToolTask.setUserInputType(0);
            writeToolTask.setContent(content);
        }
        if(StringUtils.isBlank(writeToolTask.getContent())){
            return Result.error("内容输入不完整");
        }
        writeToolTask.setWriteTool(writeTool);
        writeToolTask.setStatus(0);
        writeToolTask.setIsShow(false);
        writeToolTask.setSn(UUID.randomUUID().toString().replace("-",""));
        writeToolTaskService.save(writeToolTask);
        return Result.success(writeToolTask.getSn());
    }

    @PostMapping("/save")
    @JsonView(BaseEntity.ViewView.class)
    public Result save(String taskId){
        WriteToolTask writeToolTask = writeToolTaskService.findBySn(taskId);
        writeToolTask.setIsShow(true);
        writeToolTaskService.update(writeToolTask);
        return Result.success(writeToolTask.getSn());
    }

    @PostMapping("/history")
    @JsonView(BaseEntity.ViewView.class)
    public Result history(String toolId){
        Map<String,Object> map = new HashMap<>();
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select id,content `title`,result `content`,DATE_FORMAT(create_date,'%H:%i') `createDate` from write_tool_task order by create_date desc ;");
        map.put("list",maps);
        return Result.success(map);
    }

}
